package com.tyros.resource.modules.file.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tyros.common.constant.BaseMessage;
import com.tyros.common.exception.BaseException;
import com.tyros.common.model.PageQuery;
import com.tyros.common.service.impl.AbstractBaseServiceImpl;
import com.tyros.resource.config.property.StorageProperties;
import com.tyros.resource.constant.DataSourceConst;
import com.tyros.resource.constant.ResourceMessage;
import com.tyros.resource.modules.file.dto.FileDTO;
import com.tyros.resource.modules.file.dto.request.FilePageQueryDTO;
import com.tyros.resource.modules.file.entity.FileEntity;
import com.tyros.resource.modules.file.mapper.FileMapper;
import com.tyros.resource.modules.file.service.FileService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Optional;

/**
 * 资源文件实现类
 *
 * @author zhangshuaiyin
 * @since 1.0.0 2022-02-19
 */
@Slf4j
@Service
@AllArgsConstructor
public class FileServiceImpl extends AbstractBaseServiceImpl<FileMapper, FileEntity, FileDTO> implements FileService {
    private final StorageProperties storageProperties;

    @Override
    public FileDTO getUniqueRecord(FileDTO fileDTO) {
        return selectOne(uniqueWrapper(fileDTO));
    }

    @Override
    public FileDTO getByOpenId(String openId) {
        return Optional.ofNullable(selectOne(queryWrapper(openId))).orElseThrow(() -> new BaseException(ResourceMessage.DATABASE_FILE_EMPTY));
    }

    @Override
    public void logicDelete(FileDTO file) {
        logicUpdate(file, DataSourceConst.DELETED);
    }

    @Override
    public void logicInsert(FileDTO file) {
        logicUpdate(file, DataSourceConst.NON_DELETED);
    }

    @Override
    protected LambdaQueryWrapper<FileEntity> pageWrapper(PageQuery query) {
        FilePageQueryDTO pageQuery = (FilePageQueryDTO) query;
        return super.pageWrapper(pageQuery).eq(FileEntity::getStorageType, storageProperties.getType().getCode()).orderByDesc(FileEntity::getUpdateTime);
    }

    /**
     * 逻辑删除
     *
     * @param file    删除记录
     * @param deleted 是否删除
     */
    private void logicUpdate(FileDTO file, Integer deleted) {
        boolean update = update(file.setDeleted(deleted));
        if (!update) {
            log.error("数据库更新操作失败");
            BaseException.throwExp(BaseMessage.DATABASE_UPDATE_ERROR);
        }
    }
}
